/*
 * © 2010 Autodata Solutions Company. All Rights Reserved
 * This source code is the confidential and proprietary information of Autodata Solutions Company.
 * The user shall not, in whole or in part, copy, publish, disclose or make any use of this source code
 * without the prior written consent of Autodata Solutions Company.
 */
Ext.ns('net.autodata.modelwalk.plugins');
(function () {
	
	/**
	 * This plugin is used in place of hard coding which combobox within a model walk panel is loaded first
	 * The ModelYearLoader calls the ModelYear's store.load method
	 * @class ModelYearLoader
	 * @namespace net.autodata.modelwalk.plugins
	 */
	var Loader = Ext.extend(Object, {
		
		/**
		 * @property modelWalk
		 * @type net.autodata.modelwalk.ModelWalkPanel
		 */
		modelWalk: undefined,
			
		/**
		 * @method init
		 * @param {net.autodata.modelwalk.ModelWalkPanel} modelWalk
		 */
		init: function (modelWalk)
		{
			this.modelWalk = modelWalk;
			
			var ds = net.autodata.modelwalk.data.YearMakeModelDataStore.getInstance();
			
			modelWalk.on('destroy', this.onDestroy, this);			
			ds.on('onready', this.onReady, this);
			
			modelWalk.modelYear.getStore().on('load', this.onStoreLoad, this);
			
			//If the data store has already been loaded trigger the model year load
			if (ds.isReady) {
				this.doLoad();
			}
		},
		
		/**
		 * Calls the ModelYear's store.load method
		 * @method doLoad
		 */
		doLoad: function ()
		{
			this.modelWalk.modelYear.getStore().load();
		},
		
		/**
		 * @method onReady
		 * @private
		 */
		onReady: function ()
		{
			this.doLoad();
		},
		
		onStoreLoad: function ()
		{
			var cmy = ASC.cfg.getCurrentModelYearCode();
			var my = this.modelWalk.modelYear;
			my.setValue(cmy);
			
			var store = my.getStore();			
			var record = store.getById(cmy);
			if (record) {
				my.fireEvent('select', my, record, store.indexOf(record));
			}
		},
		
		/**
		 * Clean up any event bindings
		 * @method onDestroy
		 * @private
		 */
		onDestroy: function ()
		{
			var ds = net.autodata.modelwalk.data.YearMakeModelDataStore.getInstance();	
			ds.un('onready', this.onReady, this);
			
			this.modelWalk.modelYear.getStore().un('load', this.onStoreLoad, this);
		}
	});
	
	net.autodata.modelwalk.plugins.ModelYearLoader = Loader;
})();